package com.noahsloan.nutils.streams.clocked;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ScatteringByteChannel;

/**
 * Channel that can report it's data rate.
 * 
 * @author noah
 * 
 */
public class ClockedInputChannel implements ScatteringByteChannel {

    private final ScatteringByteChannel channel;

    private final RateCalculator calc;

    public ClockedInputChannel(ScatteringByteChannel channel) {
        this(channel, 1000);
    }

    public ClockedInputChannel(ScatteringByteChannel channel, long interval) {
        this(channel, new FixedWindowCalc(interval,
                new ClockTimer.DefaultTimeSource()));
    }

    public ClockedInputChannel(ScatteringByteChannel channel,
            RateCalculator calc) {
        super();
        this.calc = calc;
        this.channel = channel;
    }

    public long read(ByteBuffer[] dsts) throws IOException {
        long read = channel.read(dsts);
        calc.storeMeasurement(read);
        return read;
    }

    public long read(ByteBuffer[] dsts, int offset, int length)
            throws IOException {
        long read = channel.read(dsts, offset, length);
        calc.storeMeasurement(read);
        return read;
    }

    public int read(ByteBuffer dst) throws IOException {
        int read = channel.read(dst);
        calc.storeMeasurement(read);
        return read;
    }

    public void close() throws IOException {
        calc.close();
        channel.close();
    }

    public boolean isOpen() {
        return channel.isOpen();
    }

    public double getRate() {
        return calc.getRate();
    }

}
